package averageprice;

import java.io.*;
import java.util.*;

public class averageprice { 
    public static void main(String[] args) {
        File file = new File("C:\\Users\\Jntzztpp\\Desktop\\pricedata.txt"); 
        Scanner sc = null;
        FileWriter fw = null;
        int count = 0;
        double sum = 0;
        try {
            sc = new Scanner(file);
            sc.useDelimiter("[^0123456789.-]+"); 
            while (sc.hasNextDouble()) {
                double price = sc.nextDouble(); 
                count++;
                sum += price;
                
                System.out.println("价格: " + price);
            }

            if (count > 0) {
                double average = sum / count;
                String formattedAverage = String.format("%.2f", average); 
                System.out.println("平均价格：" + formattedAverage + "元/台");

                fw = new FileWriter(file, true); 
                fw.write("\n平均价格：" + formattedAverage + "元/台");
                fw.flush(); 
            } else {
                System.out.println("没有找到有效的价格数据。");
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到: " + e.getMessage());
        } catch (InputMismatchException e) {
            System.out.println("价格格式错误: 文件中包含无法解析为数字的内容。");
        } catch (IOException e) {
            System.out.println("写入文件时发生错误: " + e.getMessage());
        } finally {
            if (sc != null) {
                sc.close();
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    System.out.println("关闭FileWriter时发生错误: " + e.getMessage());
                }
            }
        }
    }
}         